package com.kaer.plugin.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import com.kaer.plugin.utils.JSONKeys;
import com.kaer.plugin.utils.NetworkUtil;
import com.kaer.plugin.utils.SharedConfig;
import com.kaer.sdk.serial.SerialReadClient;
import com.kaer.sdk.serial.update.UpdateArmHelper;
import com.kaer.sdk.utils.CardCode;
import com.kaer.sdk.utils.LogUtils;

import java.util.Calendar;

/**
 * Created by lizj on 2016/11/15.
 */

public class UpdateArmService extends Service {
    private boolean inUpdate;
    private SerialReadClient mClient;
    private String TAG = getClass().getSimpleName();
    private IntentFilter filter;
    private final int DELAY_RESPONSE = 20000;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UpdateArmHelper.UPDATE_SUCCESS:
                    SharedConfig.getInstance(UpdateArmService.this).writelongData(JSONKeys.Plugin.LAST_UPDATE, System.currentTimeMillis());
                    LogUtils.e("更新成功,开启计时");
                    closeSerialPort();
                    sendEmptyMessageDelayed(DELAY_RESPONSE, DELAY_RESPONSE);
                    break;
                case UpdateArmHelper.UPDATE_ERROR:
                    LogUtils.e("更新失败 " + msg.obj.toString());
                    inUpdate = false;
                    closeSerialPort();
                    break;
                case DELAY_RESPONSE:
                    LogUtils.e("计时结束，通知更新成功，标志位重置");
                    inUpdate = false;
                    break;
                default:
                    break;
            }


//            stopSelf();
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        filter = new IntentFilter(Intent.ACTION_TIME_TICK);
        registerReceiver(mReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "StartCommand");

        checkUpdate();


        return super.onStartCommand(intent, flags, startId);
    }

    private void checkUpdate() {
        if (!NetworkUtil.isAvailable(this)) {
            Log.i(TAG, "net isn't available");
            return;
        }
        Log.e("UpdateArmService", "checkUpdate " + inUpdate);
        if (inUpdate) {
            return;
        }
        inUpdate = !inUpdate;
        try {
            mClient = SerialReadClient.getInstance();
            int ret = mClient.openSerialPort();
            if (ret == CardCode.KT8000_Success) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mClient.checkUpdate(UpdateArmService.this, mHandler);
                    }
                }).start();
            } else
                mHandler.obtainMessage(UpdateArmHelper.UPDATE_ERROR, ret, ret, CardCode.errorCodeDescription(ret)).sendToTarget();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "action " + intent.getAction() + ",isInUpdate" + inUpdate);
            if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
                Calendar mCalendar = Calendar.getInstance();
                int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
                int minute = mCalendar.get(Calendar.MINUTE);
                Log.e(TAG, "action " + intent.getAction() + ",hour:minute " + hour + ":" + minute);
                if (hour == 2 && minute == 0) {
                    checkUpdate();
                }
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeSerialPort();
        unregisterReceiver(mReceiver);
    }

    private void closeSerialPort() {
        if (mClient != null && mClient.getSerialState() == mClient.Connected) {
            mClient.closeSerailPort();
            mClient = null;
        }
    }
}
